<template>
  <div :class="[isMore ? 'frame-nav__bar-menu-tree-more' : 'frame-nav__bar-menu-tree', `frame-nav-bg-level-${level}`]"
      >
    <template v-for="menu in menusData">
      <el-submenu v-if="menu.menuList && menu.menuList.length" :key="menu.menuKey" :index="menu.menuKey" popper-class="child-menu">
          <template slot="title">
            <template v-if="isMore && level === 1">
              <div class="menu-logo" :style="{background: menu.logoColor}">
                <i class="iconfont" :class="menu.logo ? menu.logo : 'icon-creditcard-fill'"></i>
              </div>
            </template>
            <template v-else>
              <i class="iconfont icon" :class="menu.logo"></i>
            </template>
            <span class="title nav-title" slot="title" @click="openForNav(menu)" v-html="renderMenuText(menu)"></span>
          </template>
        <bar-menu-tree :is-more="isMore" :menus="menu.menuList" :level="level + 1" :highlight-text="highlightText"></bar-menu-tree>
      </el-submenu>
      <el-menu-item v-else-if="isMore && level === 1" style="padding: 0px">
          <div style="display: flex;align-items: center;padding-left: 16px;color: rgb(89,89,89);">
            <div class="menu-logo" :style="{background: menu.logoColor}">
              <i class="iconfont" :class="menu.logo ? menu.logo : 'icon-creditcard-fill'"></i>
            </div>
            <span class="title nav-title" slot="title" @click="openForNav(menu)" v-html="renderMenuText(menu)"></span>
          </div>
      </el-menu-item>
      <el-menu-item v-else-if="isPaasAndWin(menu.menuKey)" :key="menu.menuKey" :index="menu.menuKey" :class="[{'menu-item-one':  level === 1 && !isMore},`menuKey-${menu.menuKey}`]"
        class="menu-item-simple"
        @click="openForNav(menu)">
        <i class="iconfont icon" :class="menu.logo" style="margin-right: 4px"></i>
        <span class="title" slot="title" v-html="renderMenuText(menu)"></span>
      </el-menu-item>
      <el-menu-item v-else :key="menu.menuKey" :index="menu.menuKey" :class="[{'menu-item-one' : menu.menuKey === 'M_HOME' || menu.menuKey === 'M_SYSTEM'},`menuKey-${menu.menuKey}`]"
        class="menu-item-simple"
        @click="openForNav(menu)">
        <i class="iconfont icon" :class="menu.logo"></i>
        <span class="title nav-title" slot="title" v-html="renderMenuText(menu)"></span>
      </el-menu-item>
    </template>
  </div>  
</template>
 
<script>
import { storageGet, storageSet } from '@src/util/storage';
import { platform } from '@src/platform';
import i18n from '@src/locales';
import searchTextHL from 'search-text-highlight'

const urlMap = {
  taskList: '/task',
  taskAllot: '/task/allot',
  settlement: '/balance/alreadySettlement',
  taskReview: '/task/review',
  taskClose: '/task/close',
  taskPlanList: '/task/planTask/list',
  taskPool: '/task/taskPool',
  event: '/event',
  eventOrder: '/event/order',
};

const storagePageMap = {
  taskList: 'shb_task_list_page_data',
  taskAllot: 'shb_task_allot_page_data',
  settlement: 'shb_settlement_page_data',
  taskReview: 'shb_task_review_page_data',
  taskClose: 'shb_task_close_page_data',
  taskPlanList: 'shb_task_planlist_page_data',
  taskPool: 'shb_task_taskpool_page_data',
  event: 'shb_event_list_page_data',
  eventOrder: 'shb_event_order_page_data',
};
export default {
  name: 'bar-menu-tree',
  props: {
    isColorScheme: {
      type: Object,
      default: ()=> {}
    },
    isMore: {
      type: Boolean,
      default: false
    },
    menus: {
      type: Array,
      default: () => ([])
    },
    level: {
      type: Number,
      default: 1,
    },
    highlightText: {
      type: String,
      default: '',
    }
  },
  filters: {
    filterName(menu) {
      return menu.options?.nameLanguage?.[i18n.locale] || menu.options?.name || menu.name
    }
  },
  computed: {
    menusData() {
      return this.menus.map(item => {
        if(item.options && typeof item.options === 'string') {
          item.options = JSON.parse(item.options)
        }
        if(item.options?.nameLanguage && typeof item.options?.nameLanguage === 'string') {
          item.options.nameLanguage = JSON.parse(item.options.nameLanguage)
        }
        return item
      })
    }
  },
  created() {
    // this.menusData = this.menus.map(item => {
    //   if(item.options && typeof item.options === 'string') {
    //     item.options = JSON.parse(item.options)
    //   }
    //   if(item.options?.nameLanguage && typeof item.options?.nameLanguage === 'string') {
    //     item.options.nameLanguage = JSON.parse(item.options.nameLanguage)
    //   }
    //   return item
    // })
  },
  methods: {
    isPaasAndWin(val) {
      return val.indexOf("M_PAAS") === 0 || val.indexOf("M_WINDOW") === 0;
    },
    renderMenuText(menu) {
      const menuText = menu.options?.nameLanguage?.[i18n.locale] || menu.options?.name || menu.name
      return searchTextHL.highlight(menuText, this.highlightText, { htmlTag: 'mark' })
    },
    openForNav(menu){
      // console.log('menu', menu);
      if(!menu.url) return
      // 服务商管理URL调整修改，因为AB环境后端数据库无法修改，这里需要手动修改
      if(menu.url.toLowerCase().indexOf('pcresourcemanage/servicemanage') > 0) {
        menu.url = '/serviceManage'
        menu.menuKey = 'M_SERVICE_MANAGEMENT_APP_NEW'
      }
      this.$eventBus.$emit('openForNav');
      // window.TDAPP.onEvent(
      //   `pc：访问${menu.name || `未命名页面${menu.menuKey || ''}`}`
      // );
      // 这里判断菜单打开方式
      if (menu.openType == 2) return platform.openLink(menu.url);
      let url = this.joinParams(menu.url);
      platform.openTab({
        id: menu.menuKey,
        url,
        title: menu.name,
      });
    },
    conversionUrlWithStorageName(fullUrl) {
      if (!fullUrl) return '';

      let symbol = '?';
      let symbolIndex = fullUrl.indexOf(symbol);
      let url = symbolIndex < 0 ? fullUrl : fullUrl.substr(0, symbolIndex);
      let storageKey = '';

      for (let key in urlMap) {
        if (urlMap[key] == url) {
          storageKey = key;
          break;
        }
      }

      return storagePageMap[storageKey] || '';
    },
    getStoragePageData(fullUrl) {
      let storageKey = this.conversionUrlWithStorageName(fullUrl);

      if (!storageKey) return {};

      let pageData = {};

      try {
        pageData = storageGet(storageKey, '{}');
        pageData = JSON.parse(pageData);
      } catch (err) {
        console.log('hbc: getStoragePageData -> err', err);
      }

      // 存入缓存
      if (Object.keys(pageData).length <= 0) {
        let setPageData = {
          pageSize: 10,
        };
        storageSet(storageKey, JSON.stringify(setPageData));
      }

      return pageData;
    },
    joinParams(fullUrl) {
      if (!fullUrl) return '';

      let symbol = '?';
      let symbolIndex = fullUrl.indexOf(symbol);
      let storageData = this.getStoragePageData(fullUrl);
      let url = fullUrl;
      let startIndex = 0;

      // 拼接参数
      if (symbolIndex < 0) {
        for (let key in storageData) {
          startIndex++;
          startIndex > 1
            ? (url += `&${key}=${storageData[key]}`)
            : (url += `?${key}=${storageData[key]}`);
        }
      } else {
        for (let key in storageData) {
          url += `&${key}=${storageData[key]}`;
        }
      }

      return url;
    },
  },
}
</script>
<style lang="scss">
.frame-nav__bar-menu-tree {
  --frame-nav-bg: #{$frame-nav-bg-color-level-1};

  &.frame-nav-bg-level-1 {
    --frame-nav-bg: #{$frame-nav-bg-color-level-1};
  }
  &.frame-nav-bg-level-2 {
    --frame-nav-bg: #{$frame-nav-bg-color-level-2};
  }
  &.frame-nav-bg-level-3 {
    --frame-nav-bg: #{$frame-nav-bg-color-level-3};
  }
  &.frame-nav-bg-level-1, &.frame-nav-bg-level-2 {
    .menu-item-simple:not(.menu-item-one) {
      padding-left: 36px !important;
    }
  }
  &.frame-nav-bg-level-3 .menu-item-simple:not(.menu-item-one) {
    padding-left: 50px !important;
  }

  background: var(--frame-nav-bg) !important;

  & > .el-menu-item {
    background: var(--frame-nav-bg) !important;
  }

  & > .el-submenu .el-submenu__title {
    background: var(--frame-nav-bg) !important;
  }

  .el-menu-item:hover, .el-submenu__title:hover {
    background: $color-nav-hover !important;
    color: #fff;
    ::highlight(nav-text-search-result) {
      color: #fff;
    }
    .text-highlight{
      color: #fff;
    }
  }

  .el-submenu__title {
    display: flex;
    align-items: center;

  }
  .menu-logo{
    width: 32px;
    height: 32px;
    background: $color-primary-light-5;
    border-radius: 8px; 
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    i {
      font-size: 20px;
      color: #fff;
    }
  }
  .el-menu--popup-right-start {
    .el-submenu__title .icon{
      width: 0;
    }
  }
  .el-submenu.is-opened>.el-submenu__title .el-submenu__icon-arrow{
    transform: rotate(0)!important;
  }
  .menu-item-one {
    padding-left: 16px!important;
    i {
      margin-right: 4px;
    }
  }
  .el-icon-arrow-right {
    color: #fff;
  }
  .el-menu-item.is-active {
    color: #fff;
  }
}
.frame-nav__bar-menu-tree-more {
  

  .el-menu-item:hover, .el-submenu__title:hover {
    background: #F5F7FA !important;
    color: #fff;
  }
  
  .el-menu-item.is-active {
    color: #303133!important;
  }

  .el-submenu__title {
    display: flex;
    align-items: center;

  }
  .menu-logo{
    width: 32px;
    height: 32px;
    background: $color-primary-light-5;
    border-radius: 8px; 
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 8px;
    i {
      font-size: 20px;
      color: #fff;
    }
  }
  .el-menu--popup-right-start {
    .el-submenu__title .icon{
      width: 0;
    }
  }
  .el-submenu.is-opened>.el-submenu__title .el-submenu__icon-arrow{
    transform: rotate(0)!important;
  }
  .menu-item-one {
    padding-left: 16px!important;
  }
  .el-icon-arrow-right {
    color: #fff;
  }
}
.frame-nav__bar-menu.el-menu--collapse {
  .menu-item-one {
    .el-tooltip {
      padding-left: 16px!important;
    }
  }
}

</style>
